package com.vmc.model;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MovieTransferDetailList {
	static Logger logger = LogManager.getLogger(MovieTransferDetailList.class);

	private List<MovieTransferDetail> transferList;
	
	public MovieTransferDetailList() {
		
	}
	
	public MovieTransferDetailList(List<MovieTransferDetail> list) {
		this.transferList = list;
	}
	
	public void setTransferList(List<MovieTransferDetail> list) {
		this.transferList = list;
	}

	public List<MovieTransferDetail> getTransferList() {
		return this.transferList;
	}
	
	public MovieTransferDetail getDetail(String filename) {
		if (filename != null && this.transferList != null) {
			for (MovieTransferDetail detail : this.transferList) {
				if (detail != null && detail.getSourceFilename() != null && detail.getSourceFilename().equals(filename)) {
					return detail;
				}
			}
		}
		return null;
	}
	
	public boolean isFileIncluded(File file) {
		return this.getDetail(file.getAbsolutePath()) != null;
	}
	
	public static class Builder {
		private static final String JSON = "json";
		private static ObjectMapper mapper = new ObjectMapper();
		
		public static MovieTransferDetailList build(File location) {
			List<MovieTransferDetail> transferList = new ArrayList<MovieTransferDetail>();
			logger.info("Loading Movie transfer details.");

			if (location != null && location.isDirectory()) {
				File[] jsonFiles = location.listFiles(new FilenameFilter() {

					@Override
					public boolean accept(File dir, String name) {
						return (name != null && FilenameUtils.getExtension(name).equalsIgnoreCase(JSON));
					}
					
				});
				
				if (jsonFiles != null) {
					for (File jsonFile : jsonFiles) {
						try {
							if (mapper != null) {
								MovieTransferDetail detail = MovieTransferDetail.Builder.build(jsonFile);
								logger.info("Adding detail:");
								logger.info(detail.toString());
								transferList.add(detail);
							}
						}
						catch(Exception e) {
							logger.error("Error adding " + jsonFile.getName());
						}
					}
				}
			}
			
			MovieTransferDetailList detailList = new MovieTransferDetailList(transferList);
			logger.info("Done loading Movie transfer details.");
			return detailList;
		}
	}
}
